/**
 * ActiveMQ Anonymous User - An authentication plug-in to provide 
 * access to ActiveMQ for a mix of authenticated and non-authenticated 
 * users.
 * 
 * Copyright (C) 2009 Global Radio
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.thisisglobal.util;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.activemq.security.SecurityContext;

public class SimpleAuthenticationBroker extends org.apache.activemq.security.SimpleAuthenticationBroker {
	
	private String anonymousUser = DEFAULT_ANONYMOUS_USER;
	
	private String anonymousGroup = DEFAULT_ANONYMOUS_GROUP;
	
	private static final String DEFAULT_ANONYMOUS_USER = "anonymous";
	
	private static final String DEFAULT_ANONYMOUS_GROUP = "anonymous";
	
	
	public SimpleAuthenticationBroker(Broker next, Map users, Map groups) {
		super(next, users, groups);
	}
	
	public void setAnonymousUser(String anonymousUser) {
		this.anonymousUser = anonymousUser;
	}
	
	public void setAnonymousGroup(String anonymousGroup) {
		this.anonymousGroup = anonymousGroup;
	}
	
	public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
		if(context.getSecurityContext() == null) {
			if(info.getUserName() == null && info.getPassword() == null) {
				info.setUserName(anonymousUser);
				context.setSecurityContext(new SecurityContext(info.getUserName()) {
					public Set getPrincipals() {
						Set groups = new HashSet();
						groups.add(new GroupPrincipal(anonymousGroup));
						return groups;
					}
				});
			}
		}
		super.addConnection(context, info);
	}

}
